package com.ludomancy.playground;

import java.awt.Point;
import java.util.Vector;
import com.ludomancy.gamelib.ImageStrip;
import com.ludomancy.gamelib.ResourceManager;
import com.ludomancy.gamelib.entity.EntityRadiusFilter;
import com.ludomancy.gamelib.entity.World;
import com.ludomancy.playground.items.Driller;
import com.ludomancy.playground.items.Egg;
import com.ludomancy.playground.items.Recycler;

public class Game
{
	public static Game game;
	public Terrain terrain;
	public World world;
	
	public static final int GROUND_TYPE_FLOOR = 0;
	public static final int GROUND_TYPE_WATER = 1;
	public static final int TILE_WIDTH = 24;
	public static final int TILE_HEIGHT = 28;
	
	public Game(int width, int height)
	{
		game = this;
		world = new World(width, height);
		
		// generate level
		loadTerrain(false);
		world.add(new Recycler(new Point(2*TILE_WIDTH, 1*TILE_HEIGHT)));
		world.add(new Egg(new Point(222, 33)));
		world.add(new Driller(new Point(9*TILE_WIDTH,1*TILE_HEIGHT)));
	}
	
	public void loadTerrain(boolean endGame)
	{
		if(endGame)
		{
			terrain.tiles = new ImageStrip(ResourceManager.getImage("tiles2.png"), TILE_WIDTH, TILE_HEIGHT);
			terrain.updateTerrain();			
		}
		else
		{
			terrain = new Terrain("/map.map", new ImageStrip(ResourceManager.getImage("tiles.png"), TILE_WIDTH, TILE_HEIGHT));
			terrain.updateTerrain();
		}
	}
		
	public void nukeTile(Point point)
	{
		terrain.chainBreak();
	}
	
	public Component isClose(Component center, int radius, Class clazz)
	{
		Vector c = world.getEntities(new EntityRadiusFilter(center, radius, clazz));
		if(c.isEmpty())
		{
			return null;
		}
		else
		{
			return (Component) c.elementAt(0);
		}
	}
	
	public Vector getComponents(Component center, int radius)
	{
		return world.getEntities(new EntityRadiusFilter(center, radius));
	}
		
	public Component getComponent(int x, int y)
	{
		return (Component) world.getEntityAt(new Point(x,y));
	}
		
	public void update()
	{
		terrain.update();
		world.update();
	}
	
	public Point tileFor(Point point)
	{
		return new Point(point.x/TILE_WIDTH, point.y/TILE_HEIGHT);
	}

	public void poison()
	{
		for (int y = 0; y < terrain.height; y++)
		{
			for (int x = 0; x < terrain.width; x++)
			{
				if(terrain.isWater(x, y))
				{
					terrain.map[x][y] = Terrain.TILE_POISON;
				}
			}
		}
	}

}
